import { followOrUnfollow } from "@/services/consult"
import { sendMobileCode } from "@/services/user"
import { FollowType } from "@/types/consult"
import { codeType } from "@/types/user"
import { FormInstance, showToast } from "vant"
import { onUnmounted, Ref, ref } from "vue"

export const useFollow=(type:FollowType="doc")=>{
  const loading=ref(false)
  const follow=async(item:{id:string,likeFlag:0|1})=>{
    loading.value=true
    try{
      await followOrUnfollow(item.id,type)
      item.likeFlag=item.likeFlag===1?0:1
    }finally{
      loading.value=false
    }

  }
  return {follow,loading}
}

export const useMobileCode=(mobile:Ref<string>,type:codeType='login')=>{
  //短信验证码登录
const time=ref(0)
const form=ref<FormInstance>()
let timer: number
const sendCode=async()=>{
  //检测倒计时是否结束
  if(time.value>0) return
  //验证手机号是否正确
  await form.value?.validate('mobile')
  //发送验证码
  await sendMobileCode(mobile.value,type)
  showToast('发送成功')
  time.value=60
  //开启倒计时
  if(timer) clearInterval(timer)
  timer = setInterval(() => {

    time.value--
    if(time.value<=0) clearInterval(timer)
  }, 1000);
}
onUnmounted(()=>{
  clearInterval(timer)
})
return {time,form,sendCode}

}


